<template>
  <div class="login_container">
    <el-row>
      <el-col :span="14" :xs="0"></el-col>
      <el-col :span="10" :xs="24">
        <!-- 登录的表单 -->
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h2>欢迎进入个性化食谱推荐后台</h2>
          <el-form-item prop="username">
            <el-input
              placeholder="请输入用户名"
              :prefix-icon="User"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              placeholder="请输入用户密码"
              v-model="loginForm.password"
              :prefix-icon="Lock"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="!isLogin"
            style="display: flex; flex-direction: row"
            prop="verify"
          >
            <el-input
              v-model="verify"
              placeholder="输入验证码"
              style="width: 80%; height: 35px"
            ></el-input>
            <img
              :src="captchaImg"
              @click="getCaptcha"
              style="width: 20%; height: 35px; border-radius: 5px"
            />
          </el-form-item>
          <el-form-item>
            <div
              style="
                width: 100%;
                display: flex;
                align-items: center;
                flex-direction: row-reverse;
              "
            >
              <!-- Adjust the margin and width of the link to fit your layout -->
              <el-link
                type="primary"
                style="margin-left: auto"
                @click="toSignUp"
              >
                {{ isLogin ? "注册" : "已有账号？" }}
              </el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login_btn"
              :loading="loading"
              type="primary"
              size="default"
              @click="login"
              >{{ isLogin ? "登录" : "注册" }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElNotification } from "element-plus";
import { reqImage } from "@/api/user";
import useUserStore from "@/store/modules/user";
let isLogin = ref(true);
let loading = ref(false);
let $router = useRouter();
let $route = useRoute();
let loginForm = reactive({ username: "admin", password: "123456xzj" });
let loginForms = ref();
let UserStore = useUserStore();
let verify = ref("");
const captchaImg = ref();
const captcha = ref();
onMounted(() => {
  getCaptcha();
});
const getCaptcha = async () => {
  let res = await reqImage();
  captcha.value = res.captcha;
  captchaImg.value = `data:image/png;base64,${res.image_base64}`;
  console.log(captcha);
};
const login = async () => {
  //保证校验通过
  await loginForms.value.validate();
  //按钮加载
  loading.value = true;
  if (isLogin.value == true) {
    try {
      await UserStore.userLogin(loginForm);
      //跳转
      let flag = $route.query.redirect;
      console.log("flag", flag, UserStore.mode);
      const nowPath = UserStore.mode === "admin" ? "/dishControl" : "/home";
      $router.push({ path: nowPath });
      ElNotification({
        type: "success",
        title: "登录成功",
      });
      loading.value = false;
    } catch (error) {
      console.log(error);
      loading.value = false;
      ElNotification({
        type: "error",
        title: "账户或密码错误",
      });
    }
  } else {
    try {
      await UserStore.userSignUp(loginForm);
      //跳转
      let flag = $route.query.redirect;
      $router.push({ path: flag || "/" });
      ElNotification({
        type: "success",
        title: "注册成功",
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
      ElNotification({
        type: "error",
        title: "用户已存在",
      });
    }
  }
};
const toSignUp = () => {
  isLogin.value = !isLogin.value;
  console.log(isLogin.value);
};
//自定义校验规则
const validatorUserName = (_rule, value, callback) => {
  //rule是校验规则对象，value是表单元素的文本内容,callback是回调函数
  if (value.length >= 5) {
    callback();
  } else {
    callback(new Error("账号长度至少五位"));
  }
};

const validatorPassWord = (_rule, value, callback) => {
  if (value.length >= 6) {
    callback();
  } else {
    callback(new Error("密码长度至少六位"));
  }
};
const validatorVerify = (_rule, value, callback) => {
  if (verify.value.toLowerCase() == captcha.value.toLowerCase()) {
    callback();
  } else {
    callback(new Error("验证码错误"));
    getCaptcha();
  }
};

const rules = {
  username: [
    { trigger: "change", validator: validatorUserName },
    // { required: true, message: '账号不可为空', trigger: 'blur' },
    // { required: true, min: 5, max: 10, message: '账号长度为6~10位', trigger: 'change' }
  ],
  password: [
    { trigger: "change", validator: validatorPassWord },
    // { required: true, message: '密码不可为空', trigger: 'blur' }
  ],
  verify: [{ trigger: "blur", validator: validatorVerify }],
};
</script>

<style lang="scss" scoped>
.login_container {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/backd.png") no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 50%;
    top: 30vh;
    background: url("@/assets/images/login_form.png") no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0px;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
